<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    dialogWidth="900px"
  >
    <template #searchPanel>
      <search-panel
        :showAddButton="true"
        :showFinanceButton="true"
        addTitle="新增预约"
        financeTitle="进入预约看板"
        @search="search"
        @insert="addReservation"
        @finance="actionMode"
        :addPer="'subscribe:save'"
        :financePer="'subscribeBoard:weekBoard'"
        :selectPer="'subscribe:page'"
      >
        <job-shop
          v-model="form.storeId"
          placeholder="所属门店"
        />
        <el-select
          clearable
          ref="dragSelect"
          v-model="form.memberGrade"
        >
          <el-option
            v-for="item in dict['客户会员等级']"
            :key="item.index"
            :value="item.value"
            :label="item.text"
          />
        </el-select>
        <el-select
          clearable
          ref="dragSelect"
          v-model="form.clientType"
        >
          <el-option
            v-for="item in dict['客户类型']"
            :key="item.index"
            :value="item.value"
            :label="item.text"
          />
        </el-select>
        <el-input
          clearable
          style="width: 200px"
          v-model="form.likeName"
          placeholder="请输入客户姓名/手机号/预约编号"
        />
      </search-panel>
    </template>

    <template #contentPanel>
      <el-row class="main-content">
        <el-col
          :span="12"
          class="panel1"
        >
          <el-col
            :span="24"
            align="right"
          >
            <el-button
              type="primary"
              size="mini"
              @click="thisWeek"
            >本周</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="onlyNextWeek"
            >下周</el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-caret-left"
              @click="lastWeek"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-caret-right"
              @click="nextWeek"
            ></el-button>
          </el-col>
          <el-col
            :span="24"
            class="taskPanel"
          >
            <ul>
              <li
                v-for="(item,index) in dataValueCoumlValue"
                :key="index"
              >
                <span
                  v-for="(item2,index2) in dataValueCouml"
                  :key="index2"
                  :class="{'header whiteFont':index==0,'colum':index!=0,'firstRow':index!=0&&index2==0,'isActive':item[item2.key]>0}"
                  @click="getDayDetailBoard(item2)"
                >
                <span v-if="index==0">
                  <!-- {{`${item2.label}&#x000A;${item2.labelValue||''}`}} -->
                  <div class="lineStyle" :class="{'firstRowLineStyle':index2==0}">{{item2.label}}</div>
                  <div class="lineStyle">{{item2.labelValue}}</div>
                </span>
                <span v-else>{{item[item2.key]}}</span>
                </span>
              </li>
            </ul>
          </el-col>
          <el-col
            :span="24"
            class="buttonInfo"
          >
            <span>本周总预约数：{{weekBoardInfor.sumNum}}</span>
            <span>本周转工单数：{{weekBoardInfor.turnOrderNum}}</span>
            <span>本周剩余预约：{{weekBoardInfor.num}}</span>
          </el-col>
        </el-col>
        <el-col
          :span="12"
          class="panel2"
        >
          <el-col
            :span="24"
            align="right"
          >
            <el-button
              type="primary"
              size="mini"
              @click="today"
            >今日</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="lastDay"
              icon="el-icon-caret-left"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-caret-right"
              @click="nextDay"
            ></el-button>
          </el-col>
          <el-col
            :span="24"
            class="taskPanel-day"
          >
            <el-col class="title">
              <span>{{currentDay}}</span>
              <span>已预约：{{currentDayDetail.sumNum - currentDayDetail.num}}/{{currentDayDetail.sumNum}} 已到店：{{currentDayDetail.arriveNum}}</span>
            </el-col>
            <el-col class="day-infor-panel">
              <ul>
                <li
                  v-for="(item,index) in currentDayDetail.detailList"
                  :key="index"
                  @click="workOrderInfo(item)"
                >
                  <el-col :span="12">{{item.licensePlateNumber}} <span class="panelStatus">{{item.status}}</span></el-col>
                  <el-col :span="12">
                    <svg-icon icon-class="login_user" />{{item.clientName}} {{item.phone}}
                  </el-col>
                  <el-col
                    :span="12"
                    class="colorRed"
                  >{{item.projectNames}}</el-col>
                  <el-col :span="12">
                    <svg-icon icon-class="alarmClock" />{{item.visitTime}}
                  </el-col>
                  <el-col
                    :span="24"
                    class="dottedLine"
                  >
                    <svg-icon icon-class="task" />{{item.updateTime}}
                  </el-col>
                  <el-col :span="24">{{item.remark}}</el-col>
                </li>
              </ul>
            </el-col>
            <el-col
              :span="24"
              class="buttonInfo"
            >
              <span>本日总预约数：{{currentDayDetail.sumNum}}</span>
              <span>本日转工单数：{{currentDayDetail.turnOrderNum}}</span>
              <span>本日剩余预约：{{currentDayDetail.num}}</span>
            </el-col>
          </el-col>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <dialog-view-detail
        v-if="dialogTitle=='预约详情'"
        :value="dialogData"
        @operate="handleDataOperateChange"
      />
      <AppointmentSettings v-if="dialogTitle=='预约设置'" />
    </template>

  </base-layout>
</template>

<script>
import {
  subscribeBoardWeekBoard,
  subscribeBoardDayBoard,
  subscribeBoardDayDetailBoard,
} from '@/api/after-sale/customer-center/index'
import {
  subscribeList,
  deleteSubscribe,
  affirmSubscribe,
  cancelSubscribe,
  turnWorkOrderSubscribe,
} from '@/api/after-sale/customer-center/index'
import baseMixin from '@/mixins/base'
import { getDict, getStoreId } from '@/utils'
import moment from 'moment'
import { retry } from 'rxjs/operators'
import AppointmentSettings from '../appointment-manage/AppointmentSettings'
import DialogViewDetail from '../appointment-manage/view/index.vue'

export default {
  components: {
    DialogViewDetail,
    AppointmentSettings,
  },
  mixins: [baseMixin({})],
  data() {
    return {
      dataValueCoumlValue: [],
      dataValueCouml: [
        { label: '时间', key: 'time' },
        { label: '星期一', key: 'Monday' },
        { label: '星期二', key: 'Tuesday' },
        { label: '星期三', key: 'Wednesday' },
        { label: '星期四', key: 'Thursday' },
        { label: '星期五', key: 'Friday' },
        { label: '星期六', key: 'Saturday' },
        { label: '星期日', key: 'Sunday' },
      ],
      form: {
        storeId: getStoreId(),
        clientType: '',
        likeName: '', //客户姓名/手机号码
        memberGrade: '', //客户会员等级
        mondayDate: '', //当前周周一
        sundayDate: '', //当前周周末
      },
      WeekNum: 0, //下一周开始计数
      dict: {},
      currentDay: moment(new Date()).format('YYYY-MM-DD'), //天详情显示日期
      dayNum: 0, //上下天计数
      currentDayDetail: {},
      weekBoardInfor: {},
      timetable: {}, //时刻表
    }
  },
  async created() {
    this.dict = getDict(['客户类型', '客户会员等级'])
    this.form.mondayDate = this.getWeekFirstDays()
    this.form.sundayDate = this.getWeekEndDays()
    this.thisWeek()
    // this.getCurrentDayBoard();
  },
  methods: {
    /**
     * 获取本周周一和周日日期
     */
    getCurrentWeek() {
      const start = moment().weekday(1).format('YYYY-MM-DD') //本周一
      const end = moment().weekday(7).format('YYYY-MM-DD') //本周日
      return [start, end]
    },

    /**
     * 获取前 i 周
     * @param i
     */
    getLastWeek(i) {
      let weekOfDay = parseInt(moment().format('E')) //计算今天是这周第几天
      let last_monday = moment()
        .subtract(weekOfDay + 7 * i - 1, 'days')
        .format('YYYY-MM-DD') //周一日期
      let last_sunday = moment()
        .subtract(weekOfDay + 7 * (i - 1), 'days')
        .format('YYYY-MM-DD') //周日日期
      return [last_monday, last_sunday]
    },

    /**
     * 获取后 i 周
     * @param i
     */
    getNextWeek(i) {
      let weekOfDay = parseInt(moment().format('E')) //计算今天是这周第几天
      let next_monday = moment()
        .add(7 - weekOfDay + 7 * (i - 1) + 1, 'days')
        .format('YYYY-MM-DD') //周一日期
      let next_sunday = moment()
        .add(7 - weekOfDay + 7 * i, 'days')
        .format('YYYY-MM-DD') //周日日期
      return [next_monday, next_sunday]
    },
    //获取当前或传入日期所属周的第一天
    getWeekFirstDays(day) {
      return moment(day ? day : new Date())
        .startOf('week')
        .format('YYYY-MM-DD')
    },
    getWeekEndDays(day) {
      return moment(day ? day : new Date())
        .endOf('week')
        .format('YYYY-MM-DD')
    },
    getNextDay(i) {
      return moment().add(i, 'days').format('YYYY-MM-DD')
    },
    getLastDay(i) {
      return moment().subtract(i, 'days').format('YYYY-MM-DD')
    },
    //本周
    thisWeek() {
      this.WeekNum = 0
      let _days = this.getLastWeek(Math.abs(this.WeekNum))
      this.form.mondayDate = _days[0]
      this.form.sundayDate = _days[1]
      this._subscribeBoardWeekBoard()
      this.renderWeekList(this.setWeekListDay(_days[0]))
    },
    //获取这周的下一周
    onlyNextWeek() {
      this.WeekNum = 1
      let _days = this.getNextWeek(this.WeekNum)
      this.form.mondayDate = _days[0]
      this.form.sundayDate = _days[1]
      this._subscribeBoardWeekBoard()
      this.renderWeekList(this.setWeekListDay(_days[0]))
    },
    //获取下一周
    nextWeek() {
      this.WeekNum = this.WeekNum + 1
      let _days = this.getNextWeek(this.WeekNum)
      this.form.mondayDate = _days[0]
      this.form.sundayDate = _days[1]
      this._subscribeBoardWeekBoard()
      this.renderWeekList(this.setWeekListDay(_days[0]))
    },
    //获取上一周
    lastWeek() {
      this.WeekNum = this.WeekNum - 1
      let _days =
        this.WeekNum <= 0
          ? this.getLastWeek(Math.abs(this.WeekNum))
          : this.getNextWeek(this.WeekNum)
      this.form.mondayDate = _days[0]
      this.form.sundayDate = _days[1]
      this._subscribeBoardWeekBoard()
      this.renderWeekList(this.setWeekListDay(_days[0]))
    },
    today() {
      this.currentDay = moment(new Date()).format('YYYY-MM-DD')
      this.getDayDetailBoard({ labelValue: this.currentDay })
    },
    nextDay() {
      this.dayNum = this.dayNum + 1
      this.currentDay = this.getNextDay(this.dayNum)
      this.getDayDetailBoard({ labelValue: this.currentDay })
    },
    lastDay() {
      this.dayNum = this.dayNum - 1
      this.currentDay =
        this.dayNum <= 0
          ? this.getLastDay(Math.abs(this.dayNum))
          : this.getNextDay(this.dayNum)
      this.getDayDetailBoard({ labelValue: this.currentDay })
    },
    renderWeekList(list = []) {
      let _arry = Object.assign([], this.dataValueCouml)
      list.forEach((item, index) => {
        _arry[index + 1]['labelValue'] = item
      })
      this.dataValueCouml = _arry
    },
    //生成一周数据,从每周周一开始，到周日
    setWeekListDay(day = undefined) {
      let d = []
      let _days = day || this.getWeekFirstDays(day)
      d.push(_days)
      for (let index = 0; index < 6; index++) {
        d.push(
          moment(_days)
            .add(index + 1, 'days')
            .format('YYYY-MM-DD')
        )
      }
      return d
    },
    search() {
      this._subscribeBoardWeekBoard()
      this.getDayDetailBoard({ labelValue: this.currentDay })
    },
    classificationTime(time) {
      let ty = time.split('-'),
        timeRange = [],
        atLastIndex = 0
      let num2 = ty[0].split(':')[0],
        num3 = ty[1].split(':')[0],
        num3_1 = ty[1].split(':')[1]
      Object.keys(this.timetable).forEach((item) => {
        timeRange.push(item)
      })
      let arry = timeRange.filter((item, index) => {
        let num = item.replace('t', '').split('-')[0].split(':')[0]
        if (+num >= +num2 && +num <= +num3) {
          atLastIndex = index
          return num
        }
      })
      arry.forEach((item) => {
        this.timetable[item] = this.timetable[item] + 1
      })
    },
    createdTimeObj(time) {
      if (Object.keys(this.timetable) == 0) {
        this.dataValueCoumlValue.forEach((item) => {
          this.timetable[`t${item.time}`] = 0
        })
        this.classificationTime(time)
      } else {
        this.classificationTime(time)
      }
      return this.timetable
    },
    formatWeekBoard(data) {
      let obj = {}
      if (Array.isArray(data) && data.length > 0) {
        data.forEach((item) => {
          let objKey = `d${item.subscribeDate}`
          if (objKey in obj) {
            obj[objKey] = this.createdTimeObj(item.visitTime)
          } else {
            obj[objKey] = []
            this.timetable = {} //新的日期时，缓存时刻表重置
            obj[objKey] = this.createdTimeObj(item.visitTime)
          }
        })
      }
      return obj
    },
    //预约看板查看-周
    _subscribeBoardWeekBoard() {
      subscribeBoardWeekBoard(this.form, 100, 1).then((res) => {
        if (res.success) {
          this.weekBoardInfor = res.data
          let arry = this.formatWeekBoard(res.data.subscribeDate)
          this.renderTableData((item, item2) => {
            let key = `d${item2.labelValue}`
            if (key in arry) {
              return arry[`d${item2.labelValue}`][`t${item.time}`]
            } else {
              return 0
            }
          })
          this.getDayDetailBoard({ labelValue: this.currentDay })
        }
      })
    },
    //预约看板-周-天详情
    async getDayDetailBoard(item) {
      this.form.dayDate = item.labelValue
      this.currentDay = item.labelValue
      const { data, success } = await subscribeBoardDayDetailBoard(
        this.form,
        100,
        1
      )
      if (success) {
        this.currentDayDetail = data
      }
    },
    //渲染周数据
    renderTableData(
      remderitem = () => {
        return 0
      }
    ) {
      this.dataValueCoumlValue = []
      let obj = {}
      this.dataValueCouml.forEach((item) => {
        obj[item.key] = 0
      })
      for (let index = 0; index < 10; index++) {
        this.dataValueCoumlValue.push({
          ...obj,
          time: `${index + 8}:00-${index + 9}:00`,
        })
      }
      this.dataValueCoumlValue.forEach((item1) => {
        this.dataValueCouml.forEach((item2) => {
          if (item2.key != 'time') {
            item1[item2.key] = remderitem(item1, item2)
          }
        })
      })
    },
    //工单详情
    workOrderInfo(row) {
      this.dialogVisible = true
      this.dialogTitle = '预约详情'
      this.dialogData = row
    },
    //预约详情事件处理
    handleDataOperateChange (data) {
      console.log('调阅信息', data)
      if (data.type == 1) {
        this.dialogClose();
        this.setTableData();
        return
      }
      let { type, carryInformation } = data;
      // type 2 确认 3 工单 4 取消
      let option = {
        id: carryInformation.id,
        status: type == 2 ? '等待到店' : type == 4 ? '预约取消' : '已转工单',
      }
      this.$confirm("是否确认操作", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.actionFunction(type, option, data);
        })
    },
    async actionFunction (type, option, data) {
      let { success } = type == 2 ? await affirmSubscribe(option) : type == 4 ? await cancelSubscribe(option) : await turnWorkOrderSubscribe(option.id);
      if (success) {
        this.$message.success('操作成功');
        //如果类3 预约转工单
        if (type == 3) {
          let arry = [
            { key: '快速单', type: 1, path: '/workOrderManage/create-fast' },
            { key: '综合单', type: 3, path: '/workOrderManage/create-comprehensive' },
            { key: '洗车单', type: 2, path: '/workOrderManage/create-car-wash' },
            { key: '销售单', type: 5, path: '/workOrderManage/create-sell' },];
          let orderTarge = {};
          arry.forEach(item => {
            if (item.key == data.carryInformation.subscribeWorkOrderDictValue) {
              orderTarge = item
            }
          })
          if (Object.keys(orderTarge).length > 0) {
            data.carryInformation.id = '';
            sessionStorage.setItem('pendingWorkOrder', JSON.stringify({ ...data, ...orderTarge, }));//暂存待转工单信息
            this.$router.push({
              path: orderTarge.path,
            })
          }
          return;
        }
        this.dialogClose();
        this.setTableData();
      }
    },
    //新增预约
    addReservation() {
      this.$router.push({
        path: '/customer-center/create-appointment',
      })
    },
    //进入看板模模式
    actionMode() {
      this.$router.push({
        path: '/customer-center/mode',
      })
    },
  },
  mounted() {
    this.renderTableData()
    this._subscribeBoardWeekBoard()
  },
}
</script>

<style lang="scss" scoped>
$bgc: #00a1ec;
$boderC: #ebeef5;
.taskPanel {
  border: 1px solid $boderC;
  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    width: 99%;
    display: flex;
    flex-direction: column;
    li {
      flex: 1;
      display: flex;
      span {
        flex: 1;
        display: inline-block;
        height: 80px;
        text-align: center;
        line-height: 80px;
      }
      .header {
        border-top: 1px solid $boderC;
        border-left: 1px solid $boderC;
        background-color: $bgc;
        font-size: 14px;
        line-height: 40px;
      }
      .colum {
        border-top: 1px solid $boderC;
        border-left: 1px solid $boderC;
      }
      .firstRow {
        background-color: #fdd016;
      }
      //有工位安排背景颜色
      .isActive {
        background-color: $bgc;
        color: #fff;
      }
    }
  }
}

.buttonInfo {
  // border: 1px solid red;
  display: flex;
  span {
    display: inline-block;
    flex: 1;
    text-align: center;
    height: 80px;
    line-height: 80px;
  }
}

//天详情模块
.taskPanel-day {
  border-top: 1px solid $boderC;
  display: flex;
  flex-direction: column;
  height: 96%;
  .title {
    background-color: $bgc;
    display: flex;
    flex-direction: column;
    span {
      display: inline-block;
      flex: 1;
      text-align: center;
      height: 40px;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .day-infor-panel {
    flex: 1;
    height: 100%;
    padding: 20px;
    border: 1px solid $boderC;
    overflow: hidden;
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
      height: 650px;
      overflow: auto;
      li {
        cursor: pointer;
        padding: 20px;
        border-radius: 10px;
        border: 1px solid $boderC;
        height: 208px;
        margin-bottom: 20px;
        font-size: 18px;
        .el-col {
          height: 40px;
          line-height: 40px;
        }
      }
    }
    ul::-webkit-scrollbar {
      display: none;
    }
  }
}
.panel2 {
  padding-left: 20px;
}
.main-content {
  display: flex;
  height: 100%;
}
.dottedLine {
  border-top: 3px dotted $boderC;
}
.colorRed {
  color: red;
}
.panelStatus {
  background-color: red;
  color: #fff;
  font-size: 14px;
  padding: 5px;
}
svg {
  margin-right: 10px;
}
.whiteFont {
  color: #fff;
}
.lineStyle{
  line-height: 35px;
}
.firstRowLineStyle{
  line-height: 80px;
}
</style>
